
package saxon.gui.controller;

import com.google.common.io.Files;
import java.io.File;
import java.io.IOException;
import org.apache.log4j.Logger;
import saxon.gui.model.ShellExecutor;
import saxon.gui.model.XModel;
import saxon.gui.model.XModelImpl;
import saxon.gui.view.api.XView;

/**
 *
 * @author lennyn
 */
public class XControllerImpl implements XController {
	
	private final static Logger logger = Logger.getLogger(XControllerImpl.class);

	private XView view;
	private XModel model;
	private ShellExecutor shModel;
	private String lastQuery = null;

	@Override
	public void setView(XView view) {
		this.view = view;
		this.model = new XModelImpl(view);
		this.shModel = new ShellExecutor(view);
	}

	@Override
	public void onClickExecute() {
		view.setRunning(true);
		model.processFiles();
		lastQuery = view.getInputText();
	}

	@Override
	public void onClickStop() {
		model.stopProcessing();
	}

	@Override
	public void onClickShellCommandExecute() {
		view.setRunning(true);
		shModel.executeCommand(lastQuery, view.getShellCommand());
	}

	@Override
	public void onQueryFileSelected(File file) {
		try {
			view.setInputText(new String(Files.toByteArray(file)));
		}
		catch (IOException ex) {
			String msg = "Failed to read file "+file.getPath();
			view.showError(msg);;
			logger.error(msg, ex);
		}
	}
}
